const { moviesModel } = require("../db/model/movies.js")
//获取数据库驱动
const mongoose = require("mongoose");
const get = async ({ curPage, eachPage }) => {
    (curPage = ~~curPage), (eachPage = ~~eachPage);
    const data = {
        total: 0,
        maxPage: 0,
        rows: [],
    };
    //获取当前model映射的集合中的文档总数
    data.total = await moviesModel.countDocuments();
    //获取总页数
    data.maxPage = Math.ceil(data.total / eachPage);
    const skipNum = (curPage - 1) * eachPage;
    // 获取页面渲染数据

    data.rows = await moviesModel.find().skip(skipNum).limit(eachPage).sort({ _id: -1 }).exec();

    return data

};

// query(查询条件),params(修改的属性)
const updata = async (query, params) => {
    const moviesModel = mongoose.model("movies");
    return await moviesModel.updateOne(query, params)
}
// 通过id获取数据
const getOne = async _id => {
    const moviesModel = mongoose.model("movies");
    return await moviesModel.findOne({ _id })
}
// 搜索
const searchMove = async (movie) => {
    const moviesModel = mongoose.model("movies");
    return await moviesModel.find({
        $or: [{ cname: eval(`/${movie}/`) }, { ename: eval(`/${movie}/`) }, { type: eval(`/${movie}/`) }, { area: eval(`/${movie}/`) }, { director: eval(`/${movie}/`) }, { actor: eval(`/${movie}/`) },]
    })
}
// 新增电影接口
const add = async ({ cname, ename, type, time, upDate,area,score, count, intro, isClassic, director, actor, }) => {
    const moviesModel = mongoose.model("movies");
    return await moviesModel.create({ cname, ename, type, time, area,upDate, score, count, intro, isClassic, director, actor, })
}

const findOne = async _id => {
    // model传一个参数时表示获取这个model对象
    const moviesModel = mongoose.model("movies");
    // 添加学生数据
    return await moviesModel.findOne({ _id });
}


const delPoster = async ({ _id, url }) => {
    const moviesModel = mongoose.model("movies");
    // findOne找到匹配的数据立即返回，不会接着匹配数据
    const movie = await moviesModel.findOne({ _id });
    // 删除url对应的图片，并保存！！！！！sava
    movie.poster.pull(url);
    await movie.save();
}

// 修改
// const changeMovies = async (newData) => {
//     const moviesModel = mongoose.model("movies");
//     await moviesModel.update({ _id: newData._id }, newData);
// }


// 获取所有电影 排片用的
const moviesListAll = async () => await mongoose.model("movies").find();

// 删除电影信息
const remove = async ({ _id }) => {
    const moviesModel = mongoose.model("movies");
    // cons
    await moviesModel.remove({ _id });
}
// 删除图片
const delImg = async ({ _id, url }) => {
    const moviesModel = mongoose.model("movies");
    // findOne找到匹配的数据立即返回，不会接着匹配数据
    const movie = await moviesModel.findOne({ _id });
    // 删除url对应的图片，并保存！！！！！sava
    movie.images.pull(url);
    await movie.save();
}

// 修改
const changeMovies = async (newData) => {
    const moviesModel = mongoose.model("movies");
    await moviesModel.update({ _id: newData._id }, newData);
}
module.exports = { get, add, getOne, updata, delImg, searchMove, remove, findOne, delPoster, changeMovies, moviesListAll };
